package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteCartService remoteCartService;


    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;


    @Autowired
    RabbitService rabbitService;


    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Override
    public TradeVo orderTradeData() {
        //1.调用购物车接口，获取打钩商品列表 : List<CartInfo>
        Long userId = SecurityUtils.getUserId();
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }

        List<CartInfo> cartCheckedList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartCheckedList)) {
            throw new ServiceException("数据为空!");
        }

        //2.类型转换：List<CartInfo> -> List<OrderItem>
        List<OrderItem> orderItemList = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for (CartInfo cartInfo : cartCheckedList) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);

            orderItemList.add(orderItem);

            //计算总价格
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //3.封装TradeVo
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);

        //4.未下单前，tradeNo就是交易流水号；一旦下单成功它就是我们的订单号。
        tradeVo.setTradeNo(getTradeNo(userId));
        //4.返回TradeVo
        return tradeVo;
    }


    /**
     * 下订单业务逻辑：
     * 1.验证用户重复提交表单
     * 2.验证表单参数是否空
     * 3.校验价格变化
     * 4.校验库存锁定库存
     * 5.保存订单（订单表、订单项表、订单日志表）
     * 6.删除购物车选中商品
     *
     * @param orderForm 提交订单的数据
     * @return 订单主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {

        //下订单业务逻辑：

        //1.验证用户重复提交表单
//        String tradeNo = orderForm.getTradeNo(); //交易流水号，去交易页面时生成的，并保存到redis中。用它来实现表单重复提交校验。
//        Long userId = SecurityUtils.getUserId();
//        String tradeKey = "user:trade:"+userId;
//        String tradeNoRedis = (String)redisTemplate.opsForValue().get(tradeKey); // 5分钟过期
//        if(StringUtils.isEmpty(tradeNoRedis)){ //可能过期，也可能正在处理订单业务逻辑，处理业务前已删除。
//            throw new ServiceException("不能提交表单了");
//        }
//        if(tradeNo.equals(tradeNoRedis)){
//            Boolean ifDelete = redisTemplate.delete(tradeKey);
//        }

        //上述代码不具备原子性。改进：使用Lua脚本保证原子性。
        Long userId = SecurityUtils.getUserId();
        String tradeKey = "user:trade:"+userId;
        String tradeNo = orderForm.getTradeNo();
        String script = "if(redis.call('get',KEYS[1]) == ARGV[1])\n" +
                "then " +
                "return redis.call('del',KEYS[1])\n" +
                "else " +
                "return 0 " +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long redisDeleteResult = (Long)redisTemplate.execute(redisScript, Arrays.asList(tradeKey), tradeNo);
        if(redisDeleteResult != 1){
            throw new ServiceException("不能提交表单了");
        }

        //2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if(CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("不能提交表单,数据为空");
        }

        //3.校验价格变化，提交商品价格和数据库商品价格进行比较，如果都一致，继续逻辑处理；只要有个一个商品价格不一致，取消订单，并更新购物车商品最新价格。
        //3.1准备skuIdList   从远程获取这些商品的价格  ，再进行比较价格
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList,SecurityConstants.INNER);
        if(R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();
        if(CollectionUtils.isEmpty(skuPriceList)){
            throw new ServiceException("获取商品数据失败，下单失败");
        }

        //skuPriceList -> 转换Map
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        String priceChangeResult = "";
        for (OrderItem orderItem : orderItemList) {
            BigDecimal formSkuPrice = orderItem.getSkuPrice();
            BigDecimal dbSkuPrice = skuIdToSalePriceMap.get(orderItem.getSkuId());
            if(dbSkuPrice.compareTo(formSkuPrice)!=0){ //价格不一样，记录哪个商品价格变了。再更新购物车价格
                BigDecimal subtract = dbSkuPrice.subtract(orderItem.getSkuPrice());
                priceChangeResult += orderItem.getSkuName() +"价格变了,差价："+subtract+"元; ";
            }
        }

        if(!StringUtils.isEmpty(priceChangeResult)){
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException("商品价格有变化，下单失败！"+priceChangeResult);
        }

        //4.校验库存锁定库存

        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();

        R<String> stringResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if(R.FAIL == stringResult.getCode()){
            throw new ServiceException(stringResult.getMsg());
        }
        String resultStrData = stringResult.getData();
        if(StringUtils.isNotEmpty(resultStrData)){ //不为空，说明检查库存并锁定库存出了问题了
            throw new ServiceException(resultStrData);
        }

        //5.保存订单（订单表、订单项表、订单日志表）
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);

            //int i = 1/0;
        } catch (Exception e) {
            e.printStackTrace();
            //解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());

            throw new ServiceException("下单失败！");
        }

        //6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);


        //7.下单后发送延迟消息。用于规定时间内必须支付，否则，自动取消订单。
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                orderId.toString(),
                MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    //5.保存订单（订单表、订单项表、订单日志表）
    private Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();


        //1.保存订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo()); //订单编号，就取交易流水号。
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付价格  = 商品价格 - 优惠 + 运费
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); //商品价格
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); // 订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】

        orderInfoMapper.insert(orderInfo); //主键回填

        //2.保存订单项集合数据
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            orderItemMapper.insert(orderItem);
        }


        //3.保存订单日志数据
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        //4.返回订单主键
        return orderInfo.getId();
    }


    @Override
    public TradeVo buy(Long skuId) {
        //1.调用购物车接口，获取打钩商品列表 : List<CartInfo>
        Long userId = SecurityUtils.getUserId();


        //2.根据 skuId查询商品ProductSku
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if(R.FAIL == productSkuResult.getCode()){
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();

        List<OrderItem> orderItemList = new ArrayList<>();

        OrderItem orderItem = new OrderItem();
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuNum(1);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);

        //计算总价格
        BigDecimal totalAmount = productSkuResult.getData().getSalePrice();

        //3.封装TradeVo
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);

        //4.未下单前，tradeNo就是交易流水号；一旦下单成功它就是我们的订单号。
        tradeVo.setTradeNo(getTradeNo(userId));
        //4.返回TradeVo
        return tradeVo;
    }

    /**
     * 获取交易流水号
     * @param userId
     * @return
     */
    private String getTradeNo(Long userId) {
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        String userTradeNoKey = "user:trade:" + userId;
        redisTemplate.opsForValue().set(userTradeNoKey, tradeNo, 5, TimeUnit.MINUTES); //提交订单时，用于重复提交校验。
        return tradeNo;
    }


    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityUtils.getUserId();
        //1.查询当前用户，指定状态的订单列表数据
        List<OrderInfo> orderInfoList =  orderInfoMapper.selectUserOrderInfoList(userId,orderStatus);

        //2.封装每一个订单的订单项集合属性
        if(!CollectionUtils.isEmpty(orderInfoList)){
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).toList();
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList));
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(orderIdToOrderItemListMap.get(orderInfo.getId()));
            }
        }

        //3.返回订单集合
        return orderInfoList;
    }


    @Override
    public void processCloseOrder(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(Long.parseLong(orderId));
        if(orderInfo!=null && orderInfo.getOrderStatus().intValue() == 0){ //订单不为空，而且状态为0，未支付状态就关单。
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未付款系统自动取消订单");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(Long.parseLong(orderId));
            orderLog.setOperateUser("系统");
            orderLog.setProcessStatus(-1);
            orderLog.setNote("未付款系统自动取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(orderInfo!=null && orderInfo.getOrderStatus().intValue() == 0){ //订单不为空，而且状态为0，手动关单。
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户关闭订单");
            orderInfoMapper.updateById(orderInfo);

            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderId);
            orderLog.setOperateUser("用户");
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户手动关闭订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());

            //用户点击 提交实付(已经产生本地支付信息),修改本地支付信息  支付状态
            rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_CLOSE, orderInfo.getOrderNo());
        }
    }


    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if(orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}